import Config from './config.js'
import store from '@/store/index.js'
import JSEncrypt from 'jsencrypt'
import Http from './http.js'
let timeout = null;
import config, {
	iosPhoneLoginConfig,
	androidPhoneLoginConfig
} from "@/common/js/config.js"
// #ifdef APP-PLUS
const shanYanSDKModule = uni.requireNativePlugin('CLSDK-ShanYanSDKModule')
console.log("shanYanSDKModule is", shanYanSDKModule)
const platform = uni.getSystemInfoSync().platform
// #endif
export default {
	c_price(price){
		if(!price){
			return "--"
		}
		const priceList=price.split("~")
		if(priceList[0]&&priceList[1]){
			return `${parseFloat(priceList[0])}~${parseFloat(priceList[1])}`
		}
		else if(priceList[0]){
			return parseFloat(priceList[0])
		}
	},
	//本机号码一键登录
	phoneLogin() {
		console.log("//本机号码一键登录")
		uni.showLoading({
			title:"加载中",
			mask:true
		})
		setTimeout(()=>{
			uni.hideLoading()
		},2000)
		return new Promise((resolve, reject) => {
			if (platform == "ios") {
				//一键登录
				shanYanSDKModule.quickAuthLoginWithConfigure(this.ios_uiConfigure,
					openLoginAuthListenerResult => {
						console.log("openLoginAuthListenerResult--------------",
							openLoginAuthListenerResult)
						if (openLoginAuthListenerResult.code != 1000) {
							uni.hideLoading()
							resolve(false)
						}
					},
					oneKeyLoginListenerResult => {
						//点一键登录回调	
						if (oneKeyLoginListenerResult.errorCode != null) {
							if (oneKeyLoginListenerResult.code == 1011) {
								//提示：错误无需提示给用户，可以在用户无感知的状态下直接切换登录方式
								//用户取消登录（点返回）
								//处理建议：如无特殊需求可不做处理，仅作为交互状态回调，此时已经回到当前用户自己的页面
								//点击sdk自带的返回，无论是否设置手动销毁，授权页面都会强制关闭
							} else {
								//处理建议：其他错误代码表示闪验通道无法继续，可以统一走开发者自己的其他登录方式，也可以对不同的错误单独处理
								//关闭授权页
								shanYanSDKModule.finishAuthControllerCompletion(
								oneKeyLoginListenerResult => {

								});
							}
							uni.hideLoading()
							resolve(false)
						} else {
							//SDK获取Token成功
							//此处根据token调用户后台接口获取手机号，获取成功或失败后再调shanYanSDKModule.finishAuthControllerCompletion()关闭页面
							console.log("oneKeyLoginListenerResult is", oneKeyLoginListenerResult)
							uni.hideLoading()
							let data = {
								appId: iosPhoneLoginConfig.AppID,
								mobile_token: oneKeyLoginListenerResult.data.token
							}
							let clientid = plus.push.getClientInfo().clientid;
							data.clientid = clientid;
							console.log("data is", data)
							Http.sendRequest({
								url: "/api/login/mobileauth",
								data,
								success: res => {
									if (res.code >= 0) {
										uni.setStorage({
											key: 'token',
											data: res.data.token,
											success: () => {
												// #ifdef APP-PLUS
												plus.statistic.eventTrig("login",{"from":"phoneLogin"});
												// #endif
												uni.removeStorageSync('loginLock');
												uni.removeStorageSync('unbound');
												uni.removeStorageSync('authInfo');
												store.dispatch("getUserInfo");
												uni.hideLoading()
												resolve(true)
												// //关闭授权页
												shanYanSDKModule
													.finishAuthControllerCompletion(
														oneKeyLoginListenerResult => {
															//如需跳转，code here:
														});
											}
										});
									} else {
										uni.hideLoading()
										resolve(false)
									}
								},
								fail: res => {
									uni.hideLoading()
									resolve(false)
								}
							});
						}

						// this.shanyan_code = JSON.stringify(oneKeyLoginListenerResult.code);
						// this.shanyan_result = JSON.stringify(oneKeyLoginListenerResult);
						console.log(JSON.stringify(oneKeyLoginListenerResult));
					});
			} else if (platform == "android") {
				console.log('-----')
				shanYanSDKModule.openLoginAuth(true,
					result => {
						//拉起授权页回调
						console.log("拉起授权页回调", result)
						if (result.code != 1000) {
							uni.hideLoading()
							resolve(false)
							return false
						}
					},
					result => {
						//点击登录按钮及返回键回调
						console.log("本机号码一键登录 result is", result)
						if (result.code != 1000) {
							if(result.code==1011){
								uni.hideLoading()
								resolve(true)
								return false
							}
							uni.hideLoading()
							resolve(false)
							return false
						}
						uni.hideLoading()
						// this.shanyan_code = JSON.stringify(result.code);
						// this.shanyan_result = JSON.stringify(result.result);
						let data = {
							appId: androidPhoneLoginConfig.AppID,
							mobile_token: JSON.parse(result.result).token
						}
						let clientid = plus.push.getClientInfo().clientid;
						data.clientid = clientid;
						console.log("data is", data)
						Http.sendRequest({
							url: "/api/login/mobileauth",
							data,
							success: res => {
								if (res.code >= 0) {
									uni.setStorage({
										key: 'token',
										data: res.data.token,
										success: () => {
											// #ifdef APP-PLUS
											plus.statistic.eventTrig("login",{"from":"phoneLogin"});
											// #endif
											uni.removeStorageSync('loginLock');
											uni.removeStorageSync('unbound');
											uni.removeStorageSync('authInfo');
											store.dispatch("getUserInfo");
											uni.hideLoading()
											resolve(true)
										}
									});
								} else {
									uni.hideLoading()
									resolve(false)
								}
							},
							fail: res => {
								uni.hideLoading()
								resolve(false)
							}
						})
					})
			}
		})

	},

	setAuthCJSThemeConfig(to, param, mode) {
		console.log("setAuthCJSThemeConfig-------------------------")
		let platform = uni.getSystemInfoSync().platform;
		if (platform == 'android') {
			//Android 全屏模式

			//闪验SDK  配置授权页方法
			shanYanSDKModule.setAuthThemeConfig({
				//授权页已有元素配置
				uiConfig: {
					setAuthBGImgPath: "static/banner.png",
					setNavColor: '#ff0000',
					setLogoImgPath: 'static/image/app-logo.png',
					setAppPrivacyOne: {
						title: '用户协议',
						url: config.baseUrl + "/api/protocal/platformhelp?v=html"
					},
					setAppPrivacyTwo: {
						title: '隐私政策',
						url: config.baseUrl + "/api/protocal/privacy?v=html"
					},
					setPrivacyState: false,
					setPrivacyText: {
						privacyTextOne: '登录即同意',
						privacyTextTwo: "和",
						privacyTextThree: '、',
						privacyTextFour: '',
						privacyTextFive: '并授权福袋星球获取手机号码'
					},

				}, //授权页添加自定义控件元素
				widgets: {
					widget1: {
						widgetId: "customView_one",
						type: "TextView",
						left: "",
						top: "300",
						right: "",
						bottom: "",
						width: "",
						height: "30",
						textContent: "使用其他号码登录",
						textFont: "13",
						textColor: "#333333",
						backgroundColor: "#ffffff",
						isFinish: "true"
					},
				},
			}, result => {
				console.log("setAuthCJSThemeConfig over------------------", JSON.stringify(result));
				if (result.result == "customView_one") {
					let url=to
					if (param != undefined) {
						Object.keys(param).forEach(function(key) {
							if (url.indexOf('?') != -1) {
								url += "&" + key + "=" + param[key];
							} else {
								url += "?" + key + "=" + param[key];
							}
						});
					}
					switch (mode) {
						case 'tabbar':
							// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
							uni.switchTab({
								url: url
							})
							break;
						case 'redirectTo':
							// 关闭当前页面，跳转到应用内的某个页面。
							uni.redirectTo({
								url: url
							});
							break;
						case 'reLaunch':
							// 关闭所有页面，打开到应用内的某个页面。
							uni.reLaunch({
								url: url
							});
							break;
						default:
							// 保留当前页面，跳转到应用内的某个页面
							uni.navigateTo({
								url: url
							});
					}
				}
			});
			// this.shanyan_code = 1000;
			// this.shanyan_result = "授权页配置完成";

		} else if (platform == 'ios') {
			//iOS 全屏模式

			let screenWidth_Portrait = plus.screen.resolutionWidth; //竖屏宽

			var screenScale = screenWidth_Portrait / 375.0; //相对iphone6屏幕
			if (screenScale > 1) {
				screenScale = 1; //大屏的无需放大
			}

			//竖屏
			let clLayoutLogoTop_Portrait = screenScale * 300;
			let clLayoutLogoWidth_Portrait = 60 * screenScale;
			let clLayoutLogoHeight_Portrait = 60 * screenScale;
			let clLayoutLogoCenterX_Portrait = 0;

			let clLayoutPhoneCenterY_Portrait = -20 * screenScale;
			let clLayoutPhoneLeft_Portrait = 50 * screenScale;
			let clLayoutPhoneRight_Portrait = -50 * screenScale;
			let clLayoutPhoneHeight_Portrait = 20 * screenScale;

			let clLayoutLoginBtnCenterY_Portrait = clLayoutPhoneCenterY_Portrait + clLayoutPhoneHeight_Portrait *
				0.5 *
				screenScale + 20 * screenScale + 15 * screenScale;
			let clLayoutLoginBtnHeight_Portrait = 45 * screenScale;
			let clLayoutLoginBtnLeft_Portrait = 70 * screenScale;
			let clLayoutLoginBtnRight_Portrait = -70 * screenScale;

			let clLayoutAppPrivacyLeft_Portrait = 40 * screenScale;
			let clLayoutAppPrivacyRight_Portrait = -40 * screenScale;
			let clLayoutAppPrivacyBottom_Portrait = 0 * screenScale;
			let clLayoutAppPrivacyHeight_Portrait = 45 * screenScale;

			let clLayoutSloganLeft_Portrait = 0;
			let clLayoutSloganRight_Portrait = 0;
			let clLayoutSloganHeight_Portrait = 15 * screenScale;
			let clLayoutSloganBottom_Portrait = clLayoutAppPrivacyBottom_Portrait -
				clLayoutAppPrivacyHeight_Portrait;

			//横屏 （如app本身不支持横屏，可不需设置横屏下UI配置）

			let clLayoutLogoWidth_Landscape = 60 * screenScale;
			let clLayoutLogoHeight_Landscape = 60 * screenScale;
			let clLayoutLogoCenterX_Landscape = 0;
			let clLayoutLogoCenterY_Portrait = clLayoutPhoneCenterY_Landscape - clLayoutPhoneHeight_Landscape *
				0.5 * screenScale - 60 * screenScale
			let clLayoutLogoTop_Landscape = 25 * screenScale;

			let clLayoutPhoneCenterY_Landscape = -20 * screenScale;
			let clLayoutPhoneLeft_Landscape = 50 * screenScale;
			let clLayoutPhoneRight_Landscape = -50 * screenScale;
			let clLayoutPhoneHeight_Landscape = 20 * screenScale;

			let clLayoutLoginBtnCenterY_Landscape = clLayoutPhoneCenterY_Landscape +
				clLayoutPhoneHeight_Landscape *
				0.5 *
				screenScale + 20 * screenScale + 15 * screenScale;
			let clLayoutLoginBtnHeight_Landscape = 30 * screenScale;
			let clLayoutLoginBtnLeft_Landscape = 70 * screenScale;
			let clLayoutLoginBtnRight_Landscape = -70 * screenScale;

			let clLayoutAppPrivacyLeft_Landscape = 40 * screenScale;
			let clLayoutAppPrivacyRight_Landscape = -40 * screenScale;
			let clLayoutAppPrivacyBottom_Landscape = 0 * screenScale;
			let clLayoutAppPrivacyHeight_Landscape = 45 * screenScale;

			let clLayoutSloganLeft_Landscape = 0;
			let clLayoutSloganRight_Landscape = 0;
			let clLayoutSloganHeight_Landscape = 15 * screenScale;
			let clLayoutSloganBottom_Landscape = clLayoutAppPrivacyBottom_Landscape -
				clLayoutAppPrivacyHeight_Landscape;

			this.ios_uiConfigure = {

				clBackgroundImg: "static/box.png",

				shouldAutorotate: true,
				/**支持方向
				 * 如支持横竖屏，需同时设置 clOrientationLayOutPortrait 和 clOrientationLayOutLandscape
				 * 0:UIInterfaceOrientationMaskPortrait
				 * 1:UIInterfaceOrientationMaskLandscapeLeft
				 * 2:UIInterfaceOrientationMaskLandscapeRight
				 * 3:UIInterfaceOrientationMaskPortraitUpsideDown
				 * 4:UIInterfaceOrientationMaskLandscape
				 * 5:UIInterfaceOrientationMaskAll
				 * 6:UIInterfaceOrientationMaskAllButUpsideDown
				 * */
				supportedInterfaceOrientations: 5,

				/**偏好方向 
				 * -1:UIInterfaceOrientationUnknown
				 * 0:UIInterfaceOrientationPortrait
				 * 1:UIInterfaceOrientationPortraitUpsideDown
				 * 2:UIInterfaceOrientationLandscapeLeft
				 * 3:UIInterfaceOrientationLandscapeRight
				 * */
				//偏好方向默认Portrait preferredInterfaceOrientationForPresentation: Number(5),

				clNavigationBackgroundClear: true, //导航栏透明
				clNavigationBackBtnImage: "static/img/close-white.png", //返回按钮图片
				clNavBackBtnAlimentRight: false, //返回按钮居右,设置自定义导航栏返回按钮时，以自定义为准

				clLogoImage: "static/image/app-logo.png", //logo图片
				clPhoneNumberFont: 21 * screenScale, //	手机号字体
				clLoginBtnText: "本机号一键登录", //一键登录按钮文字
				clLoginBtnTextColor: [1, 1, 1, 1.0], //rgba
				clLoginBtnBgColor: [0.54, 0.004, 1, 1.0], //rgba
				clLoginBtnTextFont: 16 * screenScale,
				clLoginBtnCornerRadius: 22,

				clPhoneNumberFont: 20.0 * screenScale,

				clAppPrivacyColor: [
					[0.6, 0.6, 0.6, 1.0],
					[0, 0.427, 1, 1.0]
				], //2 item,commomTextColor and appPrivacyTextColor
				clAppPrivacyTextFont: 11 * screenScale,
				clAppPrivacyTextAlignment: 0, //0: center 1: left 2: right
				clAppPrivacyFirst: ["《用户协议》", config.baseUrl +
					"/api/protocal/platformhelp?v=html"
				], // 2 item, name and url
				clAppPrivacySecond: ["《隐私政策》", config.baseUrl +
					"/api/protocal/privacy?v=html"
				], // 2 item, name and url

				// clCheckBoxHidden:true,
				// clCheckBoxValue:true,
				clCheckBoxVerticalAlignmentToAppPrivacyCenterY: true,
				clCheckBoxSize: [30 * screenScale, 30 * screenScale], //2 item, width and height
				clCheckBoxImageEdgeInsets: [2 * screenScale, 10 * screenScale, 13 * screenScale, 5 *
					screenScale
				], //4 item, top left bottom right
				clCheckBoxUncheckedImage: "static/image/checkbox.png",
				clCheckBoxCheckedImage: "static/image/checkbox-selected.png",

				clLoadingSize: [50, 50], //2 item, width and height
				clLoadingTintColor: [0.2, 0.8, 0.2, 1],
				clLoadingBackgroundColor: [1, 1, 1, 1],
				clLoadingCornerRadius: 5,

				//竖屏布局对象
				clOrientationLayOutPortrait: {

					clLayoutPhoneCenterY: clLayoutPhoneCenterY_Portrait,
					clLayoutPhoneHeight: clLayoutPhoneHeight_Portrait,
					clLayoutPhoneLeft: clLayoutPhoneLeft_Portrait,
					clLayoutPhoneRight: clLayoutPhoneRight_Portrait,
					//控件
					clLayoutLogoWidth: clLayoutLogoWidth_Portrait,
					clLayoutLogoHeight: clLayoutLogoHeight_Portrait,
					clLayoutLogoCenterX: clLayoutLogoCenterX_Portrait,
					clLayoutLogoCenterY:-100* screenScale,
					// clLayoutLogoTop: clLayoutLogoTop_Portrait,

					clLayoutLoginBtnCenterY: clLayoutLoginBtnCenterY_Portrait,
					clLayoutLoginBtnHeight: clLayoutLoginBtnHeight_Portrait,
					clLayoutLoginBtnLeft: clLayoutLoginBtnLeft_Portrait,
					clLayoutLoginBtnRight: clLayoutLoginBtnRight_Portrait,

					clLayoutAppPrivacyLeft: clLayoutAppPrivacyLeft_Portrait,
					clLayoutAppPrivacyRight: clLayoutAppPrivacyRight_Portrait,
					clLayoutAppPrivacyBottom: clLayoutAppPrivacyBottom_Portrait,
					clLayoutAppPrivacyHeight: clLayoutAppPrivacyHeight_Portrait,

					clLayoutSloganLeft: clLayoutSloganLeft_Portrait,
					clLayoutSloganRight: clLayoutSloganRight_Portrait,
					clLayoutSloganHeight: clLayoutSloganHeight_Portrait,
					clLayoutSloganBottom: clLayoutSloganBottom_Portrait,
				},
				//横屏布局对象 （如app本身不支持横屏，可不需设置横屏下UI配置对象）
				clOrientationLayOutLandscape: {

					//控件
					clLayoutLogoWidth: clLayoutLogoWidth_Landscape,
					clLayoutLogoHeight: clLayoutLogoHeight_Landscape,
					clLayoutLogoCenterX: clLayoutLogoCenterX_Landscape,
					clLayoutLogoTop: clLayoutLogoTop_Landscape,

					clLayoutPhoneCenterY: clLayoutPhoneCenterY_Landscape,
					clLayoutPhoneHeight: clLayoutPhoneHeight_Landscape,
					clLayoutPhoneLeft: clLayoutPhoneLeft_Landscape,
					clLayoutPhoneRight: clLayoutPhoneRight_Landscape,

					clLayoutLoginBtnCenterY: clLayoutLoginBtnCenterY_Landscape,
					clLayoutLoginBtnHeight: clLayoutLoginBtnHeight_Landscape,
					clLayoutLoginBtnLeft: clLayoutLoginBtnLeft_Landscape,
					clLayoutLoginBtnRight: clLayoutLoginBtnRight_Landscape,

					clLayoutAppPrivacyLeft: clLayoutAppPrivacyLeft_Landscape,
					clLayoutAppPrivacyRight: clLayoutAppPrivacyRight_Landscape,
					clLayoutAppPrivacyBottom: clLayoutAppPrivacyBottom_Landscape,
					clLayoutAppPrivacyHeight: clLayoutAppPrivacyHeight_Landscape,

					clLayoutSloganLeft: clLayoutSloganLeft_Landscape,
					clLayoutSloganRight: clLayoutSloganRight_Landscape,
					clLayoutSloganHeight: clLayoutSloganHeight_Landscape,
					clLayoutSloganBottom: clLayoutSloganBottom_Landscape,
				},
				//自定义控件
				widgets: {
					widget0: {
						widgetId: "customView_nav_left", //字符标记
						type: "Button", // 类型：Button：按钮，ImageView:图片 TextView:文本
						navPosition: "navleft", //按钮位置 navleft:导航栏左侧 ，navright:导航栏右侧（不设置默认添加到授权页上）,当设置为导航栏控件时，仅宽高可设置，位置固定
						textContent: "", //文字
						textFont: 11, //字体
						textColor: [1, 1, 0, 1], //文字颜色[r,g,b,a]
						// backgroundColor: [0,0,1,1],//控件背景色[r,g,b,a]
						image: "static/image/close-icon.png",
						isFinish: true, //点击销毁授权页,
						clLayoutWidth: 20,
						clLayoutHeight: 20,
					},
					widgetTitle: {
						widgetId: "widgetTitle", //字符标记
						type: "TextView", // 类型：Button：按钮，ImageView:图片 TextView:文本
						textContent: "登录/注册", //文字
						textFont: 25, //字体
						textColor: [0, 0, 0, 1], //文字颜色[r,g,b,a]
						clLayoutTop: 100,
						// clLayoutWidth: 200,
						clLayoutHeight: 25,
						clLayoutCenterX: 0,
					},
					widget1: {
						widgetId: "customView_one", //字符标记
						type: "Button", // 类型：Button：按钮，ImageView:图片 TextView:文本
						textContent: "使用其他账号登录", //文字
						textFont: 16, //字体
						textColor: [0.6, 0.6, 0.6, 1], //文字颜色[r,g,b,a]
						// image: "static/img/logo_shanyan_text.png",
						cornerRadius: 22, //圆角，设置圆角时请设置masksToBounds:true
						masksToBounds: true, //圆角相关
						isFinish: true, //点击销毁授权页
						clLayoutBottom: -100,
						clLayoutWidth: 180,
						clLayoutHeight: 50,
						clLayoutCenterX: 0,
					},
				},
			}

			//设置自定义控件点击回调
			shanYanSDKModule.setCustomInterface((customInterface) => {

				// this.shanyan_result = JSON.stringify(customInterface);
				console.log(JSON.stringify(customInterface));
				if (customInterface.widgetId == "customView_one") {
					let url=to
					if (param != undefined) {
						Object.keys(param).forEach(function(key) {
							if (url.indexOf('?') != -1) {
								url += "&" + key + "=" + param[key];
							} else {
								url += "?" + key + "=" + param[key];
							}
						});
					}
					switch (mode) {
						case 'tabbar':
							// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
							uni.switchTab({
								url: url
							})
							break;
						case 'redirectTo':
							// 关闭当前页面，跳转到应用内的某个页面。
							uni.redirectTo({
								url: url
							});
							break;
						case 'reLaunch':
							// 关闭所有页面，打开到应用内的某个页面。
							uni.reLaunch({
								url: url
							});
							break;
						default:
							// 保留当前页面，跳转到应用内的某个页面
							uni.navigateTo({
								url: url
							});
					}
				}
			});
			this.phoneLogin()
			// this.shanyan_code = 1000;
			// this.shanyan_result = "授权页配置完成";

		}
	},
	/**
	 * 页面跳转
	 * @param {string} to 跳转链接 /pages/idnex/index
	 * @param {Object} param 参数 {key : value, ...}
	 * @param {string} mode 模式 
	 */
	async redirectTo(to, param, mode) {
		let url = to;
		// console.log({"$store":store.state.$store.tabbarList.list}) 
		let tabbarList = ['/pages/index/index/index', '/pages/magic-box/index/index',
			'/pages/goods/category/category',
			'/pages/goods/cart/cart',
			'/pages/member/index/index'
		]
		for (let i = 0; i < tabbarList.length; i++) {
			if (to.indexOf(tabbarList[i]) != -1) {
				uni.switchTab({
					url: url
				})
				return;
			}
		}
		// #ifdef APP-PLUS
		if (to.indexOf("/otherpages/login/login/login") != -1) {
			//配置手机号码一键登录UI
			this.setAuthCJSThemeConfig(to, param, mode)
			//免密登录
			const flag = await this.phoneLogin()
			console.log('flag',flag)
			if (flag) {
				return true
			}
		}
		// #endif
		// // #ifdef H5
		// window.history.pushState(null, null, url);
		// // #endif

		if (param != undefined) {
			Object.keys(param).forEach(function(key) {
				if (url.indexOf('?') != -1) {
					url += "&" + key + "=" + param[key];
				} else {
					url += "?" + key + "=" + param[key];
				}
			});
		}
		switch (mode) {
			case 'tabbar':
				// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
				uni.switchTab({
					url: url
				})
				break;
			case 'redirectTo':
				// 关闭当前页面，跳转到应用内的某个页面。
				uni.redirectTo({
					url: url
				});
				break;
			case 'reLaunch':
				// 关闭所有页面，打开到应用内的某个页面。
				uni.reLaunch({
					url: url
				});
				break;
			default:
				// 保留当前页面，跳转到应用内的某个页面
				uni.navigateTo({
					url: url
				});
		}
	},
	/**
	 * 图片路径转换
	 * @param {String} img_path 图片地址
	 * @param {Object} params 参数，针对商品、相册里面的图片区分大中小，size: big、mid、small
	 */
	img(img_path, params) {
		var path = "";
		if (img_path && img_path != undefined && img_path != "") {

			// if (params && img_path != this.getDefaultImage().default_goods_img) {
			// 	// 过滤默认图
			// 	let arr = img_path.split(".");
			// 	let suffix = arr[arr.length - 1];
			// 	arr.pop();
			// 	arr[arr.length - 1] = arr[arr.length - 1] + "_" + params.size.toUpperCase();
			// 	arr.push(suffix);
			// 	img_path = arr.join(".");
			// }
			if (img_path.indexOf("http://") == -1 && img_path.indexOf("https://") == -1) {
				path = Config.imgDomain + "/" + img_path;
			} else {
				path = img_path;
			}
			// 处理商品助手的图片路径
			path = path.replace("addons/NsGoodsAssist/", "").replace("shop/goods/", "");
		}
		return path;
	},
	/**
	 * 时间戳转日期格式
	 * @param {Object} timeStamp
	 */
	timeStampTurnTime(timeStamp, type = "") {
		if (timeStamp != undefined && timeStamp != "" && timeStamp > 0) {
			var date = new Date();
			date.setTime(timeStamp * 1000);
			var y = date.getFullYear();
			var m = date.getMonth() + 1;
			m = m < 10 ? ('0' + m) : m;
			var d = date.getDate();
			d = d < 10 ? ('0' + d) : d;
			var h = date.getHours();
			h = h < 10 ? ('0' + h) : h;
			var minute = date.getMinutes();
			var second = date.getSeconds();
			minute = minute < 10 ? ('0' + minute) : minute;
			second = second < 10 ? ('0' + second) : second;
			if (type) {
				return y + '-' + m + '-' + d;
			} else {
				return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
			}

		} else {
			return "";
		}
	},
	/**
	 * 日期格式转时间戳
	 * @param {Object} timeStamp
	 */
	timeTurnTimeStamp(string) {
		var f = string.split(' ', 2);
		var d = (f[0] ? f[0] : '').split('-', 3);
		var t = (f[1] ? f[1] : '').split(':', 3);
		return (new Date(
			parseInt(d[0], 10) || null,
			(parseInt(d[1], 10) || 1) - 1,
			parseInt(d[2], 10) || null,
			parseInt(t[0], 10) || null,
			parseInt(t[1], 10) || null,
			parseInt(t[2], 10) || null
		)).getTime() / 1000;
	},
	/**
	 * 倒计时
	 * @param {Object} seconds 秒
	 */
	countDown(seconds) {
		let [day, hour, minute, second] = [0, 0, 0, 0]
		if (seconds > 0) {
			day = Math.floor(seconds / (60 * 60 * 24))
			hour = Math.floor(seconds / (60 * 60)) - (day * 24)
			minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
			second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
		}
		if (day < 10) {
			day = '0' + day
		}
		if (hour < 10) {
			hour = '0' + hour
		}
		if (minute < 10) {
			minute = '0' + minute
		}
		if (second < 10) {
			second = '0' + second
		}
		return {
			d: day,
			h: hour,
			i: minute,
			s: second
		};
	},
	/**
	 * 数值去重
	 * @param {Array} arr 数组
	 * @param {string} field 字段
	 */
	unique(arr, field) {
		const res = new Map();
		return arr.filter((a) => !res.has(a[field]) && res.set(a[field], 1));
	},
	/**
	 * 判断值是否在数组中
	 * @param {Object} elem
	 * @param {Object} arr
	 * @param {Object} i
	 */
	inArray: function(elem, arr) {
		return arr == null ? -1 : arr.indexOf(elem);
	},
	/**
	 * 获取某天日期
	 * @param {Object} day
	 */
	getDay: function(day) {
		var today = new Date();
		var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
		today.setTime(targetday_milliseconds);

		const doHandleMonth = function(month) {
			var m = month;
			if (month.toString().length == 1) {
				m = "0" + month;
			}
			return m
		}

		var tYear = today.getFullYear();
		var tMonth = today.getMonth();
		var tDate = today.getDate();
		var tWeek = today.getDay();
		var time = parseInt(today.getTime() / 1000);
		tMonth = doHandleMonth(tMonth + 1);
		tDate = doHandleMonth(tDate);

		const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
		return {
			't': time,
			'y': tYear,
			'm': tMonth,
			'd': tDate,
			'w': week[tWeek]
		};
	},
	/**
	 * 图片选择加上传
	 * @param number num
	 * @param {Object} params
	 * @param {Object} callback
	 * @param string url
	 * return array
	 */
	upload: function(num, params, callback, url) {
		// #ifdef H5
		var app_type = this.isWeiXin() ? 'wechat' : 'h5';
		var app_type_name = this.isWeiXin() ? '微信公众号' : 'H5';
		// #endif

		// #ifdef MP-WEIXIN
		var app_type = 'weapp';
		var app_type_name = '微信小程序';
		// #endif

		// #ifdef MP-ALIPAY
		var app_type = 'aliapp';
		var app_type_name = '支付宝小程序';
		// #endif

		// #ifdef MP-BAIDU
		var app_type = 'baiduapp';
		var app_type_name = '百度小程序';
		// #endif

		// #ifdef MP-TOUTIAO
		var app_type = 'MP-TOUTIAO';
		var app_type_name = '头条小程序';
		// #endif

		// #ifdef MP-QQ
		var app_type = 'MP-QQ';
		var app_type_name = 'QQ小程序';
		// #endif
		var data = {
			token: uni.getStorageSync('token'),
			app_type: app_type,
			app_type_name: app_type_name
		}
		data = Object.assign(data, params);

		// 请求参数加密
		if (Config.apiSecurity) {
			let jsencrypt = new JSEncrypt();
			jsencrypt.setPublicKey(Config.publicKey);
			let encrypt = encodeURIComponent(jsencrypt.encryptLong(JSON.stringify(data)));
			data = {
				encrypt
			};
		}
		var imgs_num = num;
		var _self = this;
		uni.chooseImage({
			count: imgs_num,
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册或者拍照
			success: async function(res) {
				const tempFilePaths = res.tempFilePaths;

				var _data = data;
				var imgs = [];
				for (var i = 0; i < tempFilePaths.length; i++) {
					var path = await _self.upload_file_server(tempFilePaths[i], _data, params.path,
						url);
					imgs.push(path);
				}
				typeof callback == 'function' && callback(imgs);
			}
		});
	},
	//上传
	upload_file_server(tempFilePath, data, path, url = "") {
		if (url) {
			var uploadUrl = Config.baseUrl + url
		} else {
			var uploadUrl = Config.baseUrl + '/api/upload/' + path
		}
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: uploadUrl,
				filePath: tempFilePath,
				name: 'file',
				formData: data,
				success: function(res) {
					var path_str = JSON.parse(res.data);
					if (path_str.code >= 0) {
						resolve(path_str.data.pic_path);
					} else {
						reject("error");
					}
				}
			});

		});

	},
	/**
	 * 复制
	 * @param {Object} message
	 * @param {Object} callback
	 */
	copy(value, callback) {
		// #ifdef H5
		var oInput = document.createElement('input'); //创建一个隐藏input（重要！）
		oInput.value = value; //赋值
		oInput.setAttribute("readonly", "readonly");
		document.body.appendChild(oInput);
		oInput.select(); // 选择对象
		document.execCommand("Copy"); // 执行浏览器复制命令
		oInput.className = 'oInput';
		oInput.style.display = 'none';
		uni.hideKeyboard();
		this.showToast({
			title: '复制成功'
		});

		typeof callback == 'function' && callback();
		// #endif

		// #ifdef MP || APP-PLUS
		uni.setClipboardData({
			data: value,
			success: () => {
				typeof callback == 'function' && callback();
			}
		});
		// #endif
	},
	/**
	 * 是否是微信浏览器
	 */
	isWeiXin() {
		// #ifndef H5
		return false;
		// #endif
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			return true;
		} else {
			return false;
		}
	},
	/**
	 * 显示消息提示框
	 *  @param {Object} params 参数
	 */
	showToast(params = {}) {
		params.title = params.title || "";
		params.icon = params.icon || "none";
		// params.position = params.position || 'bottom';
		params.duration = 1500;
		uni.showToast(params);
		// store.commit('updateShowToastValue', params)
		setTimeout(() => {
			// store.commit('updateShowToastValue', {})
		}, 1500);
		if (params.success) params.success();
	},
	/**
	 * 检测苹果X以上的手机
	 */
	isIPhoneX() {
		let res = uni.getSystemInfoSync();
		if (res.model.search('iPhone X') != -1) {
			return true;
		}
		return false;
	},
	//判断安卓还是iOS
	isAndroid() {
		let platform = uni.getSystemInfoSync().platform
		if (platform == 'ios') {
			return false;
		} else if (platform == 'android') {
			return true;
		}
	},
	/**
	 * 深度拷贝对象
	 * @param {Object} obj
	 */
	deepClone(obj) {
		const isObject = function(obj) {
			return typeof obj == 'object';
		}

		if (!isObject(obj)) {
			throw new Error('obj 不是一个对象！')
		}
		//判断传进来的是对象还是数组
		let isArray = Array.isArray(obj)
		let cloneObj = isArray ? [] : {}
		//通过for...in来拷贝
		for (let key in obj) {
			cloneObj[key] = isObject(obj[key]) ? this.deepClone(obj[key]) : obj[key]
		}
		return cloneObj
	},
	refreshBottomNav() {
		var bottomNav = uni.getStorageSync("bottom_nav");
		bottomNav = JSON.parse(bottomNav);
		for (var i = 0; i < bottomNav.list.length; i++) {
			var item = bottomNav.list[i];
			var obj = {
				index: i
			};
			obj.text = item.title;
			obj.iconPath = this.img(item.iconPath);
			obj.selectedIconPath = this.img(item.selectedIconPath);
			if (bottomNav.type == 1) {
				// 图文
			} else if (bottomNav.type == 2) {
				// 图片
			} else if (bottomNav.type == 3) {
				// 文字
			}
			// uni.setTabBarItem(obj);
		}
	},
	/**
	 * 自定义模板的跳转链接
	 * @param {Object} link
	 */
	diyRedirectTo(link, method) {
		if (link == null || link == '' || (!link.wap_url && !link.appid && !link.mobile)) return;
		if (link.wap_url.indexOf('http') != -1 || link.wap_url.indexOf('http') != -1) {
			this.redirectTo('/otherpages/web/web?src=' + link.wap_url);
		} else if (link.appid) {
			uni.navigateToMiniProgram({
				appId: link.appid,
				path: link.page
			})
		} else if (link.mobile) {
			uni.makePhoneCall({
				phoneNumber: link.mobile,
				fail: res => {
					console.log(res)
				}
			});
		} else {
			this.redirectTo(link.wap_url);
		}
	},
	/**
	 * 获取默认图
	 * @param {Object} link
	 */
	getDefaultImage() {
		let defaultImg = uni.getStorageSync('default_img');
		if (defaultImg) {
			defaultImg = JSON.parse(defaultImg);
			defaultImg.default_goods_img = this.img(defaultImg.default_goods_img);
			defaultImg.default_headimg = this.img(defaultImg.default_headimg);
			defaultImg.default_storeimg = this.img(defaultImg.default_storeimg);
			return defaultImg;
		} else {
			return {
				default_goods_img: '',
				default_headimg: '',
				default_storeimg: ''
			};
		}
	},
	/**
	 * 判断手机是否为iphoneX系列
	 */
	uniappIsIPhoneX() {
		let isIphoneX = false;
		let systemInfo = uni.getSystemInfoSync();
		// #ifdef MP
		if (systemInfo.model.search('iPhone X') != -1 || systemInfo.model.search('iPhone 11') != -1 || systemInfo.model
			.search('iPhone 12') != -1) {
			isIphoneX = true;
		}
		// #endif

		// #ifdef H5
		var u = navigator.userAgent;
		var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

		if (isIOS) {
			if (systemInfo.screenWidth == 375 && systemInfo.screenHeight == 812 && systemInfo.pixelRatio == 3) {
				isIphoneX = true;
			} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 3) {
				isIphoneX = true;
			} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 2) {
				isIphoneX = true;
			}
		}
		// #endif
		return isIphoneX;
	},
	/**
	 * 判断手机是否为iphone11系列
	 */
	uniappIsIPhone11() {
		let isIphone11 = false;
		let systemInfo = uni.getSystemInfoSync();
		// #ifdef MP
		if (systemInfo.model.search('iPhone 11') != -1) {
			isIphone11 = true;
		}
		// #endif
		return isIphone11;
	},
	/**
	 * 判断手机是否为iphoneX系列   	判断当前页面栈是否存在，如果存在，则返回该页面栈，否则跳转到该页面
	 */
	jumpPage(url) {
		let jump = true;
		let arr = getCurrentPages().reverse();
		for (let i = 0; i < arr.length; i++) {
			if (url.indexOf(arr[i].route) != -1) {
				jump = false;
				uni.navigateBack({
					delta: i
				});
				break;
			}
		}
		if (jump) {
			this.$util.diyRedirectTo(url);
		}
	},
	// 计算两个经纬度之间的距离
	getDistance(lat1, lng1, lat2, lng2) {
		var radLat1 = lat1 * Math.PI / 180.0;
		var radLat2 = lat2 * Math.PI / 180.0;
		var a = radLat1 - radLat2;
		var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378.137; // EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	},
	// #ifdef H5
	//判断该浏览器是否为safaria浏览器
	isSafari() {
		let res = uni.getSystemInfoSync();
		var ua = navigator.userAgent.toLowerCase();
		if (ua.indexOf('applewebkit') > -1 && ua.indexOf('mobile') > -1 && ua.indexOf('safari') > -1 &&
			ua.indexOf('linux') === -1 && ua.indexOf('android') === -1 && ua.indexOf('chrome') === -1 &&
			ua.indexOf('ios') === -1 && ua.indexOf('browser') === -1) {
			return true;
		} else {
			return false;
		}
	},
	// #endif
	goBack(backUrl = '/pages/index/index/index') {
		if (getCurrentPages().length == 1) {
			this.redirectTo(backUrl);
		} else {
			uni.navigateBack();
		}
	},
	numberFixed(e, f) {
		if (!f) {
			f = 0;
		}
		return Number(e).toFixed(f);
	},
	/**
	 * 获取url参数
	 */
	getUrlCode(callback) {
		var url = location.search;
		var theRequest = new Object();
		if (url.indexOf('?') != -1) {
			var str = url.substr(1);
			var strs = str.split('&');
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
			}
		}
		typeof callback == 'function' && callback(theRequest);
	},
	query_promisify(fn) {
		return new Promise((resolve, reject) => {
			fn((data) => {
				resolve(data)
			}).exec()
		})
	},
	/**
	 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
	 * 
	 * @param {Function} func 要执行的回调函数 
	 * @param {Number} wait 延时的时间
	 * @param {Boolean} immediate 是否立即执行 
	 * @return null
	 */
	debounce(func, wait = 500, immediate = false) {
		// 清除定时器
		if (timeout !== null) clearTimeout(timeout);
		// 立即执行，此类情况一般用不到
		if (immediate) {
			var callNow = !timeout;
			timeout = setTimeout(function() {
				timeout = null;
			}, wait);
			if (callNow) typeof func === 'function' && func();
		} else {
			// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
			timeout = setTimeout(function() {
				typeof func === 'function' && func();
			}, wait);
		}
	},
	/**
	 * 节流
	 * @param {*} fn
	 * @param {*} delay
	 */
	throttle(fn, waitTime = 500) {
		let isRuning = false;
		return (...args) => {
			if (!isRuning) {
				isRuning = true;
				setTimeout(() => {
					fn(args);
					isRuning = false;
				}, waitTime)
			}
		};
	},
	listenPush() {
		const _handlePush = (message) => {
			if (message.payload) {
				if (typeof message.payload == "string") {
					const path = JSON.parse(message.payload).pagePath
					console.log("click parse path", path)
					this.redirectTo(path)
				} else {
					this.redirectTo(message.payload.pagePath)
				}
			}
		};

		plus.push.addEventListener('click', (message) => {
			console.log("trigger click", message)
			_handlePush(message)
		});
		plus.push.addEventListener('receive', (message) => {
			console.log("trigger receive", message, typeof message.payload)
			let platform = uni.getSystemInfoSync().platform;
			let key
			try {
				if (message.payload && typeof message.payload == "string") {
					key = JSON.parse(message.payload).key
				}
			} catch (e) {
				//TODO handle the exception
			}
			if (message.aps) { // Apple APNS message  
				//APNS下发的消息，应用在前台  
				let _payload = {}
				if (message.payload && typeof message.payload == "object") {
					if (message.payload.payload && typeof message.payload.payload == "string") {
						message = JSON.parse(message.payload.payload)
						_payload = JSON.stringify({
							key: 'LocalMSG',
							...message.payload
						})
					}
				} else {
					_payload = JSON.stringify({
						key: 'LocalMSG'
					})
				}
				platform == "ios" && plus.push.createMessage(message.content || "您有一条新的消息~", _payload, {
					cover: false,
					title: message.title
				});
			} else if ('LocalMSG' == key) { // 特殊payload标识本地创建的消息  
				console.log("LocalMSG----")
				//本地创建的消息，通常不需要处理  
				//注意：不要在这种情况下再此调用plus.push.createMessage，从而引起循环创建本地消息  
			} else {
				console.log("接收到透传消息")
				let _payload = {}
				if (message.payload && typeof message.payload == "object") {
					_payload = JSON.stringify({
						key: 'LocalMSG',
						...message.payload
					})
				} else {
					_payload = JSON.stringify({
						key: 'LocalMSG'
					})
				}
				platform == "ios" && plus.push.createMessage(message.content || "您有一条新的消息!", _payload, {
					cover: false,
					title: message.title
				});

			}

			// _handlePush(message)
		});
	},
	// 取？拼接的
	getUrlQueryString(param, url) {
		let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
		let r = url.match(reg);
		if (r != null) {
			return r[2];
		}
		return null;
	}

}
